//
//  SecurityChangePlugin.m
//  Login
//
//  Created by Fanty on 13-12-26.
//  Copyright (c) 2013年 Fanty. All rights reserved.
//

#import "SecurityChangePlugin.h"

#import <chameleon-ios-sdk/CApplication.h>
#import <MainModuleSDK/DataCenter.h>

#import "CubeModule.h"
#import <MainModuleSDK/AsyncTask.h>
#import <SVProgressHUD/SVProgressHUD.h>

@implementation SecurityChangePlugin

-(void)securityChange:(CDVInvokedUrlCommand*)command{
    NSString* callbackId=command.callbackId;
    NSString* name =  [command.arguments objectAtIndex:0];
    
    [DataCenter defaultCenter].accountToken=@"abcdefghijklmnopqrstuvwxyz";
    [DataCenter defaultCenter].username=name;
    [DataCenter defaultCenter].roles=nil;
    [SVProgressHUD showWithStatus:@"正在获取帐户权限..." maskType:SVProgressHUDMaskTypeBlack];
    
    CubeModule* cubeModule=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Module"];
    AsyncTask* task=[cubeModule.accountManager auth];
    __block AsyncTask* __task=task;
    [task setFinishBlock:^{
        [SVProgressHUD dismiss];
        
        if([__task result]!=nil){
            [DataCenter defaultCenter].roles=[__task result];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"CubeAuth_Success" object:nil];
            [cubeModule.accountManager syncAuth:NO];
        }
        else{
            [DataCenter defaultCenter].accountToken=nil;
            [DataCenter defaultCenter].username=nil;
            if([__task statusCode]==204 || [__task statusCode]==400){
                UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:@"应用没有为该帐户授权。" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertView show];
            }
            else if([__task statusCode]==500){
                UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:@"服务器返回异常，请稍候再试。" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertView show];
                
            }
            else{
                UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:@"网络异常，请检查再试。" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertView show];
            }
            
        }
        CDVPluginResult*pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@""];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
        
        
    }];
}

@end
